package com.tl.web05.utils;

import cn.hutool.setting.Setting;

import java.sql.*;

/**
 * @author Antg
 * @date 2021/7/30 16:38
 */
public class DBUtil {
    /**
     * 注册驱动,在类加载的时候注册驱动
     */
    static {
        try {
            Class.forName(new Setting("config.setting").get("driver"));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取数据库连接驱动
     *
     * @author Antg
     * @date 2021/7/30 18:04
     */
    public static Connection getConnection(String url, String username, String password) {
        try {
            return DriverManager.getConnection(url, username, password);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return null;
        }
    }

    /**
     * 获取数据库连接,连接信息在配置文件中
     *
     * @author Antg
     * @date 2021/7/30 18:06
     */
    public static Connection getConnection() {
        Setting setting = new Setting("config.setting");
        String url = setting.get("url");
        String username = setting.get("username");
        String password = setting.get("password");
        try {
            return DriverManager.getConnection(url, username, password);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return null;
        }
    }

    /**
     * 释放资源
     *
     * @author Antg
     * @date 2021/7/30 18:43
     */
    public static void release(Connection conn, Statement stmt, ResultSet rs) {

        try {
            if (conn != null) {
                conn.close();
            }
            if (stmt != null) {
                stmt.close();
            }
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    /**
     * 释放资源
     *
     * @author Antg
     * @date 2021/7/30 18:52
     */
    public static void release(Connection conn, Statement stmt) {
        release(conn, stmt, null);
    }
}
